package online.foxnull2.foxmall.cart.web;

import online.foxnull2.foxmall.cart.service.CartService;
import online.foxnull2.foxmall.cart.vo.cart.CartItem;
import online.foxnull2.foxmall.cart.vo.cart.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class CartWebController {

    private final CartService cartService;

    @Autowired
    public CartWebController(CartService cartService) {
        this.cartService = cartService;
    }


    @GetMapping("/cart.html")
    public String cartPage(Model model) {

        CartVo cartVo = cartService.getCart();
        model.addAttribute("cart", cartVo);

        return "cart";
    }

    @GetMapping("/addCart")
    public String success(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num, RedirectAttributes redirectAttributes) {

        cartService.addToCart(skuId, num);
        redirectAttributes.addAttribute("skuId", skuId);

        return "redirect:http://cart.foxmall.com/addCart.html";
    }

    @GetMapping("/addCart.html")
    public String successPage(@RequestParam("skuId") Long skuId, Model model) {

        CartItem cartItem = cartService.getCartItemBySkuId(skuId);
        model.addAttribute("item", cartItem);

        return "success";
    }

    @GetMapping("/checkItem")
    public String checkItem(@RequestParam("skuId") Long skuId,
                            @RequestParam("checked") Integer checked) {

        cartService.checkItem(skuId, checked);

        return "redirect:http://cart.foxmall.com/cart.html";
    }

    @GetMapping("/countItem")
    public String countItem(@RequestParam("skuId") Long skuId,
                            @RequestParam("count") Integer count) {

        cartService.countItem(skuId, count);

        return "redirect:http://cart.foxmall.com/cart.html";
    }

    @GetMapping("/removeItem")
    public String removeItem(@RequestParam("skuId") Long skuId) {

        cartService.removeItem(skuId);

        return "redirect:http://cart.foxmall.com/cart.html";
    }
}
